<template funcCode="uap.dashboard.public" autoRoute="true">
  <div class="container">
    <el-splitter>
      <!-- 左侧树形菜单 -->
      <el-splitter-panel size="230px">
        <TreeMenu
          :tree-data="treeMenuData"
          :default-expanded-keys="defaultExpandedKeys"
          :default-selected-key="defaultSelectedKey"
          @selected-node="onNodeSelected"
          @create-node="onNodeCreate"
          @edit-node="onNodeEdit"
        />
      </el-splitter-panel>

      <!-- 右侧内容 -->
      <el-splitter-panel>
        <div class="table-wrapper">
          <div class="toolbar-container-left">
            <span v-if="selectedProject" class="toolbar-container-left-text">{{
              selectedProject.label
            }}</span>
          </div>
          <CToolbar
            :fields="fields"
            :search-fields="['name']"
            :visibleButtons="toolbarOptions"
            @search="handleSearch"
          >
            <template #toolbar-right-after>
              <el-button
                style="
                  margin-left: 10px;
                  margin-right: 0;
                  width: 100px;
                  height: 32px;
                "
                type="primary"
                ><el-icon color="#fff"><plus /></el-icon>
                <span class="button-text" @click="handleAddClick">添加</span>
              </el-button>
            </template>
          </CToolbar>

          <div class="table-container">
            <!-- 批量操作浮层 -->
            <CLBatchOpToolbar
              :show="showCLBatchOpToolbar"
              :show-delete="false"
              :selected-count="selectedRecords.length"
            >
              <button
                class="batch-btn"
                style="color: #d54941"
                @click="handleBatchDelete"
              >
                删除
              </button>
            </CLBatchOpToolbar>
            <CLTable
              :fields="fields"
              :initial-data="tableData"
              :tableConfig="props.tableConfig"
              :router-fields="routerFields"
              :more-actions="moreActions"
              @onMoreAction="handleMoreAction"
              @pagerChange="pagerChange"
              @show:records="handleShowRecords"
            />
          </div>
        </div>
      </el-splitter-panel>
    </el-splitter>
  </div>
  <CDialog
    :title="operate === 'create' ? '新建' : '编辑'"
    v-model="dialogVisible"
    @handleDialogOk="handleCreateOrEdit"
    :fields="dialogFields"
    :nodeData="selectedNode"
  ></CDialog>
  <MoreActionsPopup
    :visible="showMoreActionsPopup"
    :position="moreActionsPopupPosition"
    :actions="actions"
    @close="closeMoreActionsPopup"
    @action="handleMoreAction"
  />
</template>

<script setup lang="ts">
  import TreeMenu from "@/components/TreeMenu.vue";
  import CLTable from "@/components/CLTable/index.vue";
  import CToolbar from "@/components/CToolbar.vue";
  import { ref, onMounted, reactive, provide } from "vue";
  import { type ProjectNode } from "@/data/wbsData.ts";
  import { Plus } from "@element-plus/icons-vue";
  import CLBatchOpToolbar from "@/components/CLBatchOpToolbar.vue";
  import type { queryPagesType } from "./interface.ts";
  import { ElMessage, ElMessageBox } from "element-plus";
  import CDialog from "@/components/CDialog.vue";
  import { deepCopy } from "@/utils/common.ts";
  import type { DynamicField } from "@/data/wbsFields.ts";
  import { useRouter } from "vue-router";
  import { mockData } from "@/views/demo/data/data.ts";
  import MoreActionsPopup from "@/components/MoreActionsPopup.vue";

  interface TreeMenuDataProps {
    fields: DynamicField[];
    tableConfig?: Record<string, any>;
    tableData: Record<string, any>;
    treeMenuData: Record<string, any>;
    toolbarOptions?: Record<string, any>;
    moreActions?: Record<string, any>;
    routerFields?: string[];
  }
  const props = defineProps<TreeMenuDataProps>();

  const selectedProject = ref();
  const defaultExpandedKeys = ref<(string | number)[]>(["2"]); // 默认展开节点
  const defaultSelectedKey = ref<string | number>("1"); // 默认选中节点
  const showCLBatchOpToolbar = ref(false);
  const selectedRecords = ref<ProjectNode[]>([]);
  const dialogVisible = ref(false);
  const operate = ref("create");
  const selectedNode = ref({});
  const dialogFields = ref<DynamicField[]>(props.fields);
  const router = useRouter();
  const showMoreActionsPopup = ref(false);
  const moreActionsPopupPosition = ref({ left: 0, top: 0 });
  const actions = ref<Record<any, any>>([
    {
      key: "delete",
      label: "删除",
    },
    {
      key: "edit",
      label: "编辑",
    },
  ]);
  const prentNode = ref<ProjectNode | null>(null);
  // 模拟异步数据加载
  const fetchData = () => {
    selectedProject.value = (props.treeMenuData as any[]).find(
      (item) => item.id === defaultSelectedKey.value,
    );
  };
  // 选中树节点事件
  const onNodeSelected = (node: any) => {
    selectedProject.value = node;
    console.log("节点被选中:", node.label);
    //然后根据该节点来查找其下面的任务项，在重新加载数据
    props.tableData.value = JSON.parse(JSON.stringify(mockData));
  };

  // 创建树节点事件
  const onNodeCreate = (node: any) => {
    console.log("节点被创建:", node);
    dialogVisible.value = true;
    operate.value = "create";
    dialogFields.value = [
      {
        id: 1,
        name: "项目名称",
        field: "label",
        type: "text",
        invisible: true,
      },
      {
        id: 2,
        name: "父记录",
        field: "parentProject",
        type: "text",
        invisible: true,
        disable: true,
      },
      {
        id: 3,
        name: "描述",
        field: "description",
        type: "textarea",
        invisible: true,
      },
    ];
    selectedNode.value = {
      label: "",
      parentProject: node.label,
      description: "",
    };
    prentNode.value = node;
  };

  // 编辑树节点事件
  const onNodeEdit = (node: any, args: any) => {
    console.log("节点被编辑:", node);
    showMoreActionsPopup.value = true;
    moreActionsPopupPosition.value = {
      left: args.x,
      top: args.y,
    };
    dialogFields.value = [
      { id: 1, name: "项目名称", field: "name", type: "text", invisible: true },
      {
        id: 2,
        name: "父记录",
        field: "parentProject",
        type: "text",
        invisible: true,
      },
      {
        id: 3,
        name: "描述",
        field: "description",
        type: "textarea",
        invisible: true,
      },
    ];
    selectedNode.value = node;
  };

  // 处理搜索事件
  const handleSearch = (keyword: string, searchFields?: string[]) => {
    console.log("搜索关键词:", keyword);
    console.log("搜索字段:", searchFields);
    // 实际项目中，这里可以调用API搜索数据
    // 例如: await axios.get('/api/wbs/search', { params: { keyword, searchFields } });

    // 前端搜索实现 - 过滤表格数据
    if (!keyword.trim()) {
      // 如果关键词为空，恢复原始数据
      //这里应该重新根据选择的节点来重新加载数据
      props.tableData.value = JSON.parse(JSON.stringify(mockData));
      return;
    }

    // 搜索实现，根据ProjectNode结构搜索相关字段
    const filteredData = JSON.parse(JSON.stringify(mockData));

    // 默认搜索字段
    const defaultSearchFields = ["name", "assignee", "status"];
    // 使用传入的搜索字段或默认字段
    const fieldsToSearch = searchFields?.length
      ? searchFields
      : defaultSearchFields;

    const searchInTree = (data: ProjectNode[]): ProjectNode[] => {
      return data.filter((node): boolean => {
        // 搜索当前节点
        let matchesSearch = false;

        // 根据指定的字段进行搜索
        for (const field of fieldsToSearch) {
          if (
            node[field as keyof ProjectNode] &&
            String(node[field as keyof ProjectNode])
              .toLowerCase()
              .includes(keyword.toLowerCase())
          ) {
            matchesSearch = true;
            break;
          }
        }
        // 如果有子节点，递归搜索
        // if (node.children && node.children.length > 0) {
        //   node.children = searchInTree(node.children);
        //   // 如果当前节点不匹配但子节点有匹配，也保留当前节点
        //   return matchesSearch || (node.children && node.children.length > 0);
        // }
        return matchesSearch;
      });
    };
    props.tableData.value = searchInTree(filteredData);
  };
  // 更新节点的钩子函数
  const handleUpdateNode = (node: ProjectNode, field: string, value: any) => {
    console.log("更新节点:", node, field, value);

    // 实际项目中，这里应该调用API更新数据
    // 例如: await axios.put('/api/wbs/update', { id: node.id, field, value });

    // 这里仅作前端演示，实际更新逻辑由wbsTable组件内部处理
    // 如果需要在父组件中处理更新逻辑，可以在这里实现
  };

  // 处理更多操作
  const handleMoreAction = async (action: string, node: ProjectNode) => {
    // console.log("handleMoreAction", action, node);
    try {
      switch (action) {
        case "delete":
          // 确认删除
          await ElMessageBox.confirm(
            `确定要删除项目"${node.name}"吗？`,
            "删除确认",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
            },
          );
          await handleDeleteNode(node);
          break;

        case "edit":
          // 编辑项目逻辑
          console.log("编辑项目:", selectedNode.value);
          selectedNode.value = deepCopy(node);
          dialogVisible.value = true;
          operate.value = "edit";
          // ElMessage.info("编辑项目功能待实现");
          break;

        case "layoutSetting":
          // 布局设置逻辑
          console.log("布局设置:", node);
          // ElMessage.info("布局设置功能待实现");
          router.push("/design");
          break;

        case "switch":
          console.log("点击按钮:", node);
          handleUpdateNode(node.originData.id, node.field, node.originData);
          break;

        default:
          console.warn("未知操作:", action);
      }
    } catch (error) {
      if (error !== "cancel") {
        console.error("操作失败:", error);
        ElMessage.error("操作失败，请重试");
      }
    }
  };
  const tableListQuery = reactive<queryPagesType>({
    pageNo: 1,
    pageSize: 10,
    sortParams: [],
    conditions: [],
  });
  // 定义缺失的函数
  const handleDeleteNode = async (node: ProjectNode) => {
    // 模拟删除操作
    console.log("删除节点:", node);
    ElMessage.success("删除成功");
  };

  const handleShowRecordDetail = (node: ProjectNode) => {
    console.log("查看详情:", node);
  };

  const handleFavoriteProject = async (node: ProjectNode) => {
    console.log("收藏项目:", node);
  };

  const getMoreActions = (node: ProjectNode) => {
    return props.moreActions;
  };

  // 处理添加按钮点击事件
  const handleAddClick = () => {
    // 显示添加对话框的逻辑
    ElMessage.info("添加功能待实现");
    console.log("添加按钮被点击");

    // 如果需要可以打开添加记录的对话框
    // 这里可以根据项目需求实现具体的添加逻辑
  };

  // const listProject = async (params: any) => {
  //   // 模拟API调用
  //   return { result: tableData.value, total: tableData.value.length };
  // };

  // 使用tableListQuery替代pages
  const pagerChange = (pager: { currentPage: number; pageSize: number }) => {
    tableListQuery.pageSize = pager.pageSize;
    tableListQuery.pageNo = pager.currentPage;
  };

  // 从后端获取表格数据
  // const fetchTableData = async () => {
  //   try {
  //     const res: any = await listProject({
  //       page: tableListQuery.pageNo,
  //       pageSize: tableListQuery.pageSize,
  //       conditions: tableListQuery.conditions,
  //       sortParams: tableListQuery.sortParams,
  //     });
  //     // 兼容不同返回结构：优先使用 res.list，否则使用 res.data/list/records 等常见字段
  //     res?.result?.forEach((i: any) => {
  //       if (i.name && typeof i.name === "object" && i.name["zh_CN"]) {
  //         i.name = i.name["zh_CN"];
  //       }
  //     });
  //     tableData.value = Array.isArray(res.result) ? res.result : [];
  //     // 由于没有pages变量，这里不设置total
  //   } catch (error) {}
  // };

  // 批量操作相关状态
  const showCLBatchOpToolbarGantt = ref(false);

  const handleShowRecords = (records: ProjectNode[]) => {
    console.log("handleShowRecords", records);
    selectedRecords.value = records;
    showCLBatchOpToolbar.value = records.length > 0;
    showCLBatchOpToolbarGantt.value = records.length > 0;
  };

  // 处理批量删除操作
  const handleBatchDelete = () => {
    if (selectedRecords.value.length === 0) return;

    // 调用删除节点的函数处理批量删除
    selectedRecords.value.forEach((record) => {
      handleDeleteNode(record);
    });

    // 删除完成后清空选中状态
    selectedRecords.value = [];
    showCLBatchOpToolbar.value = false;
    showCLBatchOpToolbarGantt.value = false;
  };
  const handleCreateOrEdit = async (formData: Record<string, any>) => {
    // console.log(formData, "handleCreateOrEdit");
    if (operate.value === "edit") {
      props.tableData.forEach((item, index) => {
        if (item.id === selectedNode.value.id) {
          props.tableData[index] = { ...item, ...formData };
        }
      });
      dialogVisible.value = false;
      selectedNode.value = {};
    } else if (operate.value === "create") {
      console.log(formData, "handleCreateOrEdit", prentNode.value);
      if (prentNode.value?.children) prentNode.value.children.push(formData);
      else prentNode.value.children = [formData];
      console.log(props.treeMenuData, "handleCreateOrEdit", prentNode.value);
      dialogVisible.value = false;
      selectedNode.value = {};
    } else {
      ElMessage.error("操作失败，请重试");
    }
  };
  const closeMoreActionsPopup = () => {
    showMoreActionsPopup.value = false;
  };
  // 显示字段配置弹窗
  const showFieldConfigPopup = () => {};
  provide("showFieldConfigPopup", showFieldConfigPopup);
  onMounted(() => {
    fetchData();
  });
</script>

<style scoped lang="scss">
  .container {
    height: 100vh;
  }
  .table-wrapper {
    height: 100%;
  }
  .table-container {
    background-color: #fff;
    padding: 0 20px;
    margin-top: 20px;
    position: relative;
  }
  /* 滚动条样式 */
  .table-container::-webkit-scrollbar {
    width: 6px;
    height: 6px;
  }
  .table-container::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
  }
  .table-container::-webkit-scrollbar-thumb {
    background: #888;
    border-radius: 3px;
  }
  .table-container::-webkit-scrollbar-thumb:hover {
    background: #555;
  }
  .toolbar-container-left {
    position: relative;
    top: 15px;
    left: 25px;
    height: 25px;
    display: flex;
    align-items: center;
    width: 50%;
  }
  .toolbar-container-left-text {
    font-size: 18px;
    font-weight: 500;
  }
  :deep(.toolbar-container) {
    right: 24px;
  }
  :deep(.el-button--primary) {
    background-color: #1aa1fb;
    border: 1px solid #1aa1fb;
    &:hover {
      background-color: rgba(26, 161, 251, 0.5);
      border: 1px solid rgba(26, 161, 251, 0.4);
    }
  }
  .button-text {
    font-size: 14px;
    font-weight: 500;
    margin-left: 4px;
  }
  .batch-btn {
    //padding: 4px 12px;
    background-color: #fff;
    border: 1px solid #d9d9d9;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s;
    font-size: 14px;
    color: #42464e;
    height: 28px;
    width: 48px;
  }

  .batch-btn:hover {
    color: #42464e;
    background-color: rgba(31, 35, 41, 0.1);
  }
</style>
